//
//  ViewController.m
//  二维码
//
//  Created by 李东喜 on 15/12/9.
//  Copyright © 2015年 don. All rights reserved.
//

#import "QRViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "WWebViewController.h"

@interface QRViewController ()<UITabBarDelegate,AVCaptureMetadataOutputObjectsDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UITabBar *customBar;
@property (weak, nonatomic) IBOutlet UIImageView *scanLineImageView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *containerHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scanLineTopConstraint;
@property (weak, nonatomic) IBOutlet UILabel *customLabel;
@property (weak, nonatomic) IBOutlet UIView *customContainerView;

@property ( strong , nonatomic ) AVCaptureDevice * device;
@property ( strong , nonatomic ) AVCaptureDeviceInput * input;
@property ( strong , nonatomic ) AVCaptureMetadataOutput * output;
@property ( strong , nonatomic ) AVCaptureSession * session;
@property ( strong , nonatomic ) AVCaptureVideoPreviewLayer * previewLayer;

/*** 专门用于保存描边的图层 ***/
@property (nonatomic,strong) CALayer *containerLayer;
@end

@implementation QRViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.customBar.selectedItem = self.customBar.items.firstObject;
    self.customBar.delegate = self;

    // 3.开始扫描二维码
    [self startScan];
}
- (IBAction)closeButtonClick:(id)sender {

    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)openCameralClick:(id)sender {

    // 1.判断相册是否可以打开
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
    // 2. 创建图片选择控制器
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];

    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    // 4.设置代理
    ipc.delegate = self;

    // 5.modal出这个控制器
    [self presentViewController:ipc animated:YES completion:nil];
}

#pragma mark -------- UIImagePickerControllerDelegate---------
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    // 1.取出选中的图片
    UIImage *pickImage = info[UIImagePickerControllerOriginalImage];
    NSData *imageData = UIImagePNGRepresentation(pickImage);

    CIImage *ciImage = [CIImage imageWithData:imageData];

    // 2.从选中的图片中读取二维码数据
    // 2.1创建一个探测器
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];

    // 2.2利用探测器探测数据
    NSArray *feature = [detector featuresInImage:ciImage];

    // 2.3取出探测到的数据
    for (CIQRCodeFeature *result in feature) {
        WLog(@"%@",result.messageString);
        NSString *urlStr = result.messageString;
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
    }

    // 注意: 如果实现了该方法, 当选中一张图片时系统就不会自动关闭相册控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -------- 懒加载---------
- (AVCaptureDevice *)device
{
    if (_device == nil) {
        _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    }
    return _device;
}

- (AVCaptureDeviceInput *)input
{
    if (_input == nil) {
        _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    }
    return _input;
}

- (AVCaptureSession *)session
{
    if (_session == nil) {
        _session = [[AVCaptureSession alloc] init];
    }
    return _session;
}

- (AVCaptureVideoPreviewLayer *)previewLayer
{
    if (_previewLayer == nil) {
        _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    }
    return _previewLayer;
}

// 设置输出对象解析数据时感兴趣的范围
// 默认值是 CGRect(x: 0, y: 0, width: 1, height: 1)
// 通过对这个值的观察, 我们发现传入的是比例
// 注意: 参照是以横屏的左上角作为, 而不是以竖屏
//        out.rectOfInterest = CGRect(x: 0, y: 0, width: 0.5, height: 0.5)
- (AVCaptureMetadataOutput *)output
{
    if (_output == nil) {
        _output = [[AVCaptureMetadataOutput alloc] init];

        // 1.获取屏幕的frame
        CGRect viewRect = CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT);
        // 2.获取扫描容器的frame
        CGRect containerRect = self.customContainerView.frame;

        CGFloat x = containerRect.origin.y / viewRect.size.height;
        CGFloat y = containerRect.origin.x / viewRect.size.width;
        CGFloat width = containerRect.size.height / viewRect.size.height;
        CGFloat height = containerRect.size.width / viewRect.size.width;

         CGRect outRect = CGRectMake(x, y, width, height);
         [_output rectForMetadataOutputRectOfInterest:outRect];
//        _output.rectOfInterest = CGRectMake(x, y, width, height);
    }
    return _output;
}

- (CALayer *)containerLayer
{
    if (_containerLayer == nil) {
        _containerLayer = [[CALayer alloc] init];
    }
    return _containerLayer;
}
/*---------------------------- 分割线 ---------------------------- */
- (void)startScan
{
    // 1.判断输入能否添加到会话中
    if (![self.session canAddInput:self.input]) return;
    [self.session addInput:self.input];


    // 2.判断输出能够添加到会话中
    if (![self.session canAddOutput:self.output]) return;
    [self.session addOutput:self.output];

    // 4.设置输出能够解析的数据类型
    // 注意点: 设置数据类型一定要在输出对象添加到会话之后才能设置
    self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code];


    // 5.设置监听监听输出解析到的数据
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

    // 6.添加预览图层
    [self.view.layer insertSublayer:self.previewLayer atIndex:0];
    self.previewLayer.frame = CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT);
    // self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

    // 7.添加容器图层
    [self.view.layer addSublayer:self.containerLayer];
    self.containerLayer.frame = CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT);

    // 8.开始扫描
    [self.session startRunning];
}

#pragma mark --------AVCaptureMetadataOutputObjectsDelegate ---------
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    WLog(@"来到了代理方法");
    NSString *zhQRcode = nil;
    for (AVMetadataObject *metadata in metadataObjects) {

        if ([metadata.type isEqualToString:AVMetadataObjectTypeQRCode]) {
            zhQRcode = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
            NSArray *arr = [zhQRcode componentsSeparatedByString:@","];
            if(arr.count==9||arr.count==8){
                NSString *fpdm = arr[2];
                NSString *fphm = arr[3];
                NSString *kjje = arr[4];
                NSString *kprq = arr[5];

                if(![self acq:kprq]){
                    [WShareUtil showAlert:@"温馨提示" message:@"开票日期已超过1年"];
                }else{
                    //afcdm(fpdm);
                   NSString *fplx = [self alxd:fpdm];
                    if([fplx isEqualToString:@"04"]||[fplx isEqualToString:@"10"]||[fplx isEqualToString:@"11"]){
                        NSString *kjje = arr[6];
                        kjje = [kjje substringWithRange:NSMakeRange(kjje.length - 6, 6)];
                    }
                    WWebViewController *webVc = [[WWebViewController alloc] init];
                    webVc.strUrl = [NSString stringWithFormat:@"http://fpcy.sx95113.com/iv/yzm.html?fpdm=%@&fphm=%@&kjje=%@&kprq=%@",fpdm,fphm,kjje,kprq];
                    [self.navigationController pushViewController:webVc animated:YES];
                }
            }else{
                [WShareUtil showAlert:@"温馨提示" message:@"扫描数据错误"];
            }
            break;
        }
    }
    WLog(@"QR Code -- %@",zhQRcode);
    [_session stopRunning];

//    //  if (metadataObjects.count > 0) {
//    // id 类型不能点语法,所以要先去取出数组中对象
//    AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
//
//    if (object == nil) return;
//    // 只要扫描到结果就会调用
////    self.customLabel.text = object.stringValue;
//    [self clearLayers];
//
//    // [self.previewLayer removeFromSuperlayer];
//
//    // 2.对扫描到的二维码进行描边
//    AVMetadataMachineReadableCodeObject *obj = (AVMetadataMachineReadableCodeObject *)[self.previewLayer transformedMetadataObjectForMetadataObject:object];
//
//    [self drawLine:obj];
//    // 停止扫描
//    //        [self.session stopRunning];
//    //
//    //        // 将预览图层移除
//    //        [self.previewLayer removeFromSuperlayer];
//    //    } else {
//    //        WLog(@"没有扫描到数据");
//    //    }
}

// 绘制描边
- (void)drawLine:(AVMetadataMachineReadableCodeObject *)objc
{
    NSArray *array = objc.corners;

    // 1.创建形状图层, 用于保存绘制的矩形
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];

    // 设置线宽
    layer.lineWidth = 2;
    layer.strokeColor = [UIColor greenColor].CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;

    // 2.创建UIBezierPath, 绘制矩形
    UIBezierPath *path = [[UIBezierPath alloc] init];
    CGPoint point = CGPointZero;
    int index = 0;

    CFDictionaryRef dict = (__bridge CFDictionaryRef)(array[index++]);
    // 把点转换为不可变字典
    // 把字典转换为点，存在point里，成功返回true 其他false
    CGPointMakeWithDictionaryRepresentation(dict, &point);

    [path moveToPoint:point];

    // 2.2连接其它线段
    for (int i = 1; i<array.count; i++) {
        CGPointMakeWithDictionaryRepresentation((__bridge CFDictionaryRef)array[i], &point);
        [path addLineToPoint:point];
    }
    // 2.3关闭路径
    [path closePath];

    layer.path = path.CGPath;
    // 3.将用于保存矩形的图层添加到界面上
    [self.containerLayer addSublayer:layer];
}

- (void)clearLayers
{
    if (self.containerLayer.sublayers)
    {
        for (CALayer *subLayer in self.containerLayer.sublayers)
        {
            [subLayer removeFromSuperlayer];
        }
    }
}

//注意，在界面消失的时候关闭session
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.session stopRunning];
}

// 界面显示,开始动画
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self startAnimation];
}

// 开启冲击波动画
- (void)startAnimation
{
    // 1.设置冲击波底部和容器视图顶部对齐
    self.scanLineTopConstraint.constant = - self.containerHeightConstraint.constant;
    // 刷新UI
    [self.view layoutIfNeeded];

    // 2.执行扫描动画
    [UIView animateWithDuration:1.0 animations:^{
        // 无线重复动画
        [UIView setAnimationRepeatCount:MAXFLOAT];
        self.scanLineTopConstraint.constant = self.containerHeightConstraint.constant;
        // 刷新UI
        [self.view layoutIfNeeded];
    } completion:nil];
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    // 根据当前选中的按钮重新设置二维码容器高度
    self.containerHeightConstraint.constant = item.tag == 1 ? 150 : 300;
    // 刷新UI
    [self.view layoutIfNeeded];

    // 移除动画
    [self.scanLineImageView.layer removeAllAnimations];

    [self startAnimation];
}

-(NSString *)alxd:(NSString *)a{
    NSString *b;
    NSString *c = @"99";

    //特殊发票种类
    NSArray *code = [NSArray arrayWithObjects:@"144031539110",@"131001570151",@"133011501118",@"111001571071",nil];
    NSArray *code10 = [NSArray arrayWithObjects:@"1440315391",@"1310015701",@"1330115011",@"1110015710",nil];

    if(a.length==12){
        b = [a substringWithRange:NSMakeRange(7, 1)];
        for(int i=0; i<code.count; i++){
            if([a isEqualToString:code[i]]){
                c=@"10";
                break;
            }
        }
        if ([c isEqualToString:@"99"]) {  //增加判断，判断是否为新版电子票
            if ([a characterAtIndex:0] == '0' && [[a substringWithRange:NSMakeRange(10, 2)] isEqualToString:@"11"]) {
                c= @"10";
            }
            if (([a characterAtIndex:0] == '0') && ([[a substringWithRange:NSMakeRange(10, 2)] isEqualToString:@"06"] || [[a substringWithRange:NSMakeRange(10, 2)] isEqualToString:@"07"])) {  //判断是否为卷式发票  第1位为0且第11-12位为06或07
                c = @"11";
            }
        }
        if([c isEqualToString: @"99"]){ //如果还是99，且第8位是2，则是机动车发票
            if ([b isEqualToString:@"2"] && [a characterAtIndex:0] != '0') {
                c= @"03";
            }
        }

    }else if(a.length==10){
        b=[a substringWithRange:NSMakeRange(7, 2)];
        if([b isEqualToString:@"1"]||[b isEqualToString:@"5"]){
            c = @"01";
        }else if([b isEqualToString:@"6"]||[b isEqualToString:@"3"]){
            c = @"04";
        }else if([b isEqualToString:@"7"]||[b isEqualToString:@"2"]){
            c = @"02";
        }
    }
    return c;
}

- (NSString *)acq:(NSString *)a {
    NSString *b = @"^\\d{8}$";
    NSString *c = @"^0{8}$";
    NSString *d= @"^0{11}-?[1-9]*\\w\\d*$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", b];
    if([pred evaluateWithObject:a]){
        NSDateComponents *g = [self getCurrentNSDateComponents];
        NSInteger h = g.year;
        NSInteger i = g.month;
        NSInteger j = [[self getCurrentTime] integerValue];
        NSInteger k = [[a substringWithRange:NSMakeRange(0, 4)] integerValue];
        NSInteger l =  [[a substringWithRange:NSMakeRange(4, 2)] integerValue];
        NSInteger m =  [[a substringWithRange:NSMakeRange(6, 1)] integerValue];
        NSInteger n = [self ca:0];
        NSInteger t = [self ca:1];
        if((h!=k&&h-1!=k)||l == 0 || l>12|| m == 0 || m>31 || a.integerValue>n||![self cb:k b:l c:m] ||(h==k && i== l && j==m)){
            return false;
        }
        if(h-1==k&&a.integerValue<=t){
            return false;
        }
        return @"true";
    }else{
        return @"false";
    }
}

- (NSInteger)cb:(NSInteger)a b:(NSInteger)b c:(NSInteger)c{
    if(c>31){
        return false;
    }else if(c<1){
        return false;
    }else{
        if(b==2){
            if(c>29){//2月不会超过29
                return false;
            }

            if (((a%4)==0) && ((a%100)!=0) || ((a % 400)==0)) {//闰年1--29
                return true;
            }else{//平年1--28
                if(c>28){
                    return false;
                }
            }
        }else if((b==4||b==6||b==9||b==11)&&c>30){
            return false;
        }
    }
    return true;
}

- (NSInteger)ca:(int)i {
    NSDateComponents *a = [self getCurrentNSDateComponents];
    NSInteger b = 0;
    NSInteger c = 0;
    NSString *d;
    NSString *e = @"";
    b = a.year - i;
    c = a.month;
    d = [self getCurrentTime];
    e = [NSString stringWithFormat:@"%@%ld",e,b];
    if (c >= 10 ){
        e = [NSString stringWithFormat:@"%@%ld",e,c];
    }else{
        e = [NSString stringWithFormat:@"%@0%ld",e,c];
    }
    if (d.integerValue >= 10 ){
        e = [NSString stringWithFormat:@"%@%@",e,d];
    }else{
        e = [NSString stringWithFormat:@"%@0%@",e,d];
    }
    return e.integerValue;

}

//获取当地时间
- (NSDateComponents *)getCurrentNSDateComponents {
    // 获取代表公历的NSCalendar对象
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate* dt = [NSDate date];
    // 定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    // 获取不同时间字段的信息
    NSDateComponents* comp = [gregorian components: unitFlags
                                          fromDate:dt];
    // 获取各时间字段的数值
    WLog(@"现在是%ld年" , comp.year);
    WLog(@"现在是%ld月 " , comp.month);
    WLog(@"现在是%ld日" , comp.day);
    WLog(@"现在是%ld时" , comp.hour);
    WLog(@"现在是%ld分" , comp.minute);
    WLog(@"现在是%ld秒" , comp.second);
    WLog(@"现在是星期%ld" , comp.weekday);

    return comp;
}

//获取当地时间
- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMdd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

@end
